spin_sleep
Accurate sleeping. Only use native sleep as far as it can be trusted, then spin.
The problem with thread::sleep
is it isn't always very accurate, and this accuracy varies
on platform and state. Spinning is as accurate as we can get, but consumes the CPU
rather ungracefully.
This library adds a middle ground, using a configurable native accuracy setting allowing thread::sleep to wait the bulk of a sleep time, and spin the final section to guarantee accuracy.
SpinSleeper
Simplist usage with default native accuracy is a drop in replacement for thread::sleep
.
extern crate spin_sleep;
sleep;
More advanced usage, including setting a custom native accuracy, can be achieved by
constructing a SpinSleeper
.
// Create a new sleeper that trusts native thread::sleep with 100μs accuracy
let spin_sleeper = new;
// Sleep for 1.01255 seconds, this will:
// - thread:sleep for 1.01245 seconds, ie 100μs less than the requested duration
// - spin until total 1.01255 seconds have elapsed
spin_sleeper.sleep;
Sleep can also requested in f64
seconds or u64
nanoseconds
(useful when used with time
crate)
spin_sleeper.sleep_s;
spin_sleeper.sleep_ns;
OS-specific default accuracy settings should be good enough for most cases.
let sleeper = default;
LoopHelper
For controlling & report rates (e.g. game FPS) this crate provides LoopHelper
. A SpinSleeper
is used to maximise
sleeping accuracy.
use LoopHelper;
let mut loop_helper = builder
.report_interval_s // report every half a second
.build_with_target_rate; // limit to 250 FPS if possible
let mut current_fps = None;
loop
Windows Accuracy
Windows has particularly poor accuracy by default (~15ms), spin_sleep
will automatically
select the best accuracy on windows generally achieving ~1ms native sleep accuracy (Since 0.3.3).